#!usr/bin/env python3
from flask import Flask,render_template
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CsrfProtect
from flask_login import LoginManager
from flask_pagedown import PageDown
from config import config,getLang
from .jinjaFilters import setFilters
from flask_debugtoolbar import DebugToolbarExtension



bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
csrf = CsrfProtect()
pageDown = PageDown() 

login_manager = LoginManager() #创建登陆认证管理器
login_manager.sesstion_protection = "strong" #设置保护等级(可取值:None basic strong)
login_manager.login_view = "auth.login" #设置登录的视图函数
login_manager.login_message = getLang('notLogin')

def create_app(config_name): #利用工厂函数创建APP
	app = Flask(__name__)
	app.config.from_object(config[config_name])
	toolbar = DebugToolbarExtension(app)
	setFilters(app) #注册自定义的模板过滤函数	
	app.debug = True
	bootstrap.init_app(app)
	mail.init_app(app)
	moment.init_app(app)
	db.init_app(app)
	db.app = app
	csrf.init_app(app)
	pageDown.init_app(app)	

	login_manager.init_app(app) #初始化登陆认证管理器
	#附加路由和自定义的错误页面
	from .main import main as main_blueprint #用as语法重命名 可以防止相同模块名的BUG 
	from .auth import auth as auth_blueprint
	from .admin import admin as admin_blueprint
	from .api_v1_0 import api as api_v1_0_BP

	app.register_blueprint(main_blueprint) #注册蓝本,以便可以定义路由和错误页面
	app.register_blueprint(auth_blueprint,url_prefix="/auth") #注册登陆授权相关的蓝本,url_prefix 定义路由的前缀
	app.register_blueprint(admin_blueprint,url_prefix='/admin') #注册后台管理相关的蓝本,
	app.register_blueprint(api_v1_0_BP,url_prefix="/api/v1.0") #注册api蓝本 
	return app

